# coding:utf-8
"""
生成标签
"""

import json
import os
import cv2

train_file = "data/lslm/train1.txt"
savdir = "data/lslm/labels"
imagedir = "data/lslm/images"
with open(train_file) as f:
    lines = f.readlines()
    for line in lines:
        line = line.strip()
        items = line.split()
        name = items[0]
        print(name)
        imgpath = os.path.join(imagedir, name)
        im = cv2.imread(imgpath)
        height,width, _ = im.shape
        print(im.shape)
        objects = []

        labelpath = os.path.join(savdir, name.replace(".jpg",".txt"))
        f = open(labelpath, 'w')
        for item in items[1:]:
            print(item)
            data = json.loads(item)
            value = data['value']
            coordinate = data['coordinate']
            x1 = coordinate[0][0]
            y1 = coordinate[0][1]
            x2 = coordinate[1][0]
            y2 = coordinate[1][1]
            print(x1, y1, x2 , y2)
            cx = (x1 + x2) / 2
            cy = (y1 + y2) / 2
            w = x2 - x1
            h = y2 - y1
            cx_s = cx / width
            cy_s = cy / height
            w_s = w / width
            h_s = h /height
            if value=="bolt":
                value = 0
            else:
                value = 1
            line = "{} {} {} {} {}\n".format(value, cx_s, cy_s, w_s, h_s)
            if cx_s > 1 or cy_s > 1 or w_s > 1 or h_s > 1:
                print(name)
            print(line)
            f.write(line)
        f.close()
